import { cloneDeep } from 'lodash'

export default {
  data () {
    return {
      dialogVisible: false,
      loading: false,
      openType: '',
    }
  },
  computed: {
    // 弹窗标题
    modalTitle () {
      return `${this.openType}${this.title}`
    },
    // 判断是否为查看
    onlyShow () {
      return this.openType === '查看'
    },
    // 按钮文字
    okText () {
      return this.openType === '查看' ? '修改' : '确定'
    },
  },
  /**
   * 监听属性 (深度 deep 首次 immediate)
   */
  watch: {
    /**
     * 监听弹窗关闭(重置)
     */
    dialogVisible (newVal) {
      !newVal && this.resetForm()
    },
  },
  methods: {
    /**
     * 初始化
     */
    init (row, openType) {
      this.openType = openType
      this.dialogVisible = true
      if (row) {
        // eslint-disable-next-line no-unused-vars
        const { comreq, _index, _rowKey, ...one } = cloneDeep(row)
        this.model.dataForm = one
      } else {
        this.model.dataForm.id = ''
      }
    },
    /**
     * 重置
     */
    resetForm () {
      this.$refs.form.resetFields()
    },
    /**
     * 关闭按钮loading
     */
    closeLoading () {
      this.loading = false
    },
    /**
     * @description 关闭弹窗
     */
    handleClose () {
      this.loading = false
      this.dialogVisible = false
    },
    /**
     * 提交数据，校验
     */
    handleSubmit (e, name = 'form') {
      if (this.onlyShow) {
        this.openType = '修改'
      } else {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.submitData()
          }
        })
      }
    },
    /**
     * 提交数据，调用接口
     */
    async submitData () {
      this.loading = true
      const method = this.model.dataForm.id ? 'update' : 'add'
      this.API[method](this.model.dataForm)
        .then((msg) => {
          this.$message.success(msg)
          this.handleClose()
          this.$emit('refreshDataList', this.model.dataForm)
        })
        .catch((error) => {
          this.closeLoading()
          error && this.$message.error(error.message)
        })
    },
    /**
     * 打开删除弹窗
     *
     * @param {*} row
     *
     */
    openDelete (row, title) {
      this.$nextTick(() => {
        this.$confirm(`确定删除此条${title}?`, `删除${title}`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
        })
          .then(() => {
            this.sureDelete(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      })
    },
    /**
     * @description:确认删除
     * @param {*}
     * @return {*}
     */
    async sureDelete (row) {
      try {
        const msgSuccess = await this.API.del(row)
        this.$message.success(msgSuccess)
        this.$router.history.go(-1)
      } catch (error) {
        error && this.$message.error(error.message)
      }
    },
  },
}
